package com.ptmall.app.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ptmall.app.BuildConfig;
import com.ptmall.app.MainActivity;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.bean.WeixinBean;
import com.ptmall.app.bean.model.db.Account;
import com.ptmall.app.bean.model.db.DBHelper;
import com.ptmall.app.bean.model.db.dao.AccountDao;
import com.ptmall.app.net.NetUtils;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.utils.SharedPreferenceUtil;
import com.ptmall.app.view.TitleBarView;
import com.xfly.app.wxapi.WxLogin;
import com.xfly.app.wxapi.WxLoginResultListener;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;

import okhttp3.Call;
import okhttp3.Response;

public class LoginActivity extends BaseMvpActivity implements View.OnClickListener {

    TitleBarView titlebar;
    LinearLayout wx_login;

    private Intent intent;
    private Button login;
    private TextView regight_text, regipwd;
    private EditText phone, pass;
    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();
    private AccountDao mAccountDao = DBHelper.getInstance().getAccountDao();
    // 获取第一步的code后，请求以下链接获取access_token
    private String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    // 获取用户个人信息
    private String GetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_login);
    }

    @Override
    public void initViews() {
        wx_login = (LinearLayout) findViewById(R.id.wx_login);
        regipwd = (TextView) findViewById(R.id.regipwd);
        titlebar = (TitleBarView) findViewById(R.id.titlebar);
        regight_text = (TextView) findViewById(R.id.regight_text);
        phone = (EditText) findViewById(R.id.phone);
        pass = (EditText) findViewById(R.id.pass);
        titlebar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {
                intent = new Intent(getContext(), SpeedLoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
        findViewById(R.id.yhxy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                startActivity(new Intent(getContext(), GzActivity.class));
            }
        });
        login = (Button) findViewById(R.id.login);
        regipwd.setOnClickListener(this);
        login.setOnClickListener(this);
        wx_login.setOnClickListener(this);
        regight_text.setOnClickListener(this);
    }

    @Override
    public void initEvents() {

        phone.setText(SharedPreferenceUtil.getSharedStringData(getContext(),"loginid"));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login:
                login();


                break;
            case R.id.regight_text:
                intent = new Intent(getContext(), RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.regipwd:

                intent = new Intent(getContext(), RegisterPassActivity.class);
                startActivity(intent);
                break;
            case R.id.wx_login:
                WxLogin.getInstance().login(new WxLoginResultListener() {
                    @Override
                    public void onSuccess(String code) {//获取成功
                        Log.i("xucc", code);
                        StringBuffer loginUrl = new StringBuffer();
                        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                                .append("?appid=")
                                .append(BuildConfig.WEIXIN_APP_ID)
                                .append("&secret=")
                                .append("7e1c04cccb29d974150da02c8ade9c3d")
                                .append("&code=")
                                .append(code)
                                .append("&grant_type=authorization_code");
    /*
             * 将你前面得到的AppID、AppSecret、code，拼接成URL 获取access_token等等的信息(微信)
			 */
                        String get_access_token = getCodeRequest(code);
                        Map<String, String> reqBody = new ConcurrentSkipListMap<>();
                        NetUtils netUtils = NetUtils.getInstance();
                        netUtils.postDataAsynToNet(get_access_token, reqBody,
                                new NetUtils.MyNetCall() {
                                    @Override
                                    public void success(Call call, Response response)
                                            throws IOException {

                                        String responseData = response.body().string();
                                        parseJSONWithGSON(responseData);

                                    }

                                    @Override
                                    public void failed(Call call, IOException e) {

                                    }

                                });


                        //获取用户信息
//                        Map<String,String> map = new HashMap<>();
//                        map.put("openid",code);
//                        apiDataRepository.wxlogin(map, new ApiNetResponse<Account>() {
//                            @Override
//                            public void onSuccess(Account account) {
//                                try {
//                                    //reSetAccount();
//                                    mAccountDao.queryBuilder().where(AccountDao.Properties.MemberId.eq(account.memberId)).buildDelete().forCurrentThread().executeDeleteWithoutDetachingEntities();
//                                    account.current = 1;
//                                    App.getInstance().setAccount(account);
//                                    mAccountDao.insertOrReplace(account);
//                                    if(TextUtils.isEmpty(account.tel)){
//                                        Intent intent = new Intent(getContext(),WxLoginActivity.class);
//                                        intent.putExtra("id",account.memberId+"");
//                                        startActivity(intent);
//                                        finish();
//                                    }else {
//                                        finish();
//
//                                    }
//                                    Log.i("xucc", "===============" + account.toString());
//                                } catch (Exception e1) {
//                                    Log.i("xucc", Log.getStackTraceString(e1));
//                                } finally {
//                                }
//                            }
//                        });

                    }

                    @Override
                    public void onError(String errorDetail) {//获取失败
                        if (!TextUtils.isEmpty(errorDetail)) {
                            showMsg(errorDetail);
                        }
                    }

                    @Override
                    public void onCancel() {//取消
                        showMsg("取消");
                    }
                });
                break;
        }
    }

    private void login() {
        Map<String, String> map = new HashMap<>();
        map.put("tel", phone.getText().toString());
        map.put("password", pass.getText().toString());
        apiDataRepository.login(map, new ApiNetResponse<Account>(getContext()) {
            @Override
            public void onSuccess(Account account) {
                try {
                    //reSetAccount();
                    MainActivity.MEMBERID = account.memberId+"";
                    SharedPreferenceUtil.setSharedStringData(LoginActivity.this,"memberId",account.memberId+"");

                    SharedPreferenceUtil.setSharedStringData(LoginActivity.this,"loginid",phone.getText().toString());
                    finish();
                    Log.i("xucc", "===============" + account.toString());
                } catch (Exception e1) {
                    Log.i("xucc", Log.getStackTraceString(e1));
                } finally {
                }
            }
        });
    }


    /**
     * 通过拼接的用户信息url获取用户信息
     *
     * @param user_info_url
     */
    private void getUserInfo(String user_info_url) {
        Map<String, String> reqBody = new ConcurrentSkipListMap<>();
        NetUtils netUtils = NetUtils.getInstance();
        netUtils.postDataAsynToNet(user_info_url, reqBody,
                new NetUtils.MyNetCall() {
                    @Override
                    public void success(Call call, Response response) throws IOException {
                        String str = response.body().string();
                        parseJSONUser(str);

                    }

                    @Override
                    public void failed(Call call, IOException e) {

                    }

                });

    }


    // 解析用户信息
    private void parseJSONUser(String jsonData) {
        Log.i("xucc", jsonData);
        // 使用轻量级的Gson解析得到的json
        Gson gson = new Gson();
        WeixinBean weixinBean = gson.fromJson(jsonData,
                new TypeToken<WeixinBean>() {
                }.getType());
        // 控制台输出结果，便于查看
                        Map<String,String> map = new HashMap<>();
                        map.put("openid",weixinBean.getOpenid());
                        map.put("nickName",weixinBean.getNickname());
                        map.put("image_head",weixinBean.getHeadimgurl());
                        apiDataRepository.wxlogin(map, new ApiNetResponse<Account>() {
                            @Override
                            public void onSuccess(Account account) {
                                try {
                                    MainActivity.MEMBERID = account.memberId+"";
                                    SharedPreferenceUtil.setSharedStringData(LoginActivity.this,"memberId",account.memberId+"");
                                    if(TextUtils.isEmpty(account.tel)){
                                        Intent intent = new Intent(getContext(),WxLoginActivity.class);
                                        intent.putExtra("id",account.memberId+"");
                                        startActivity(intent);
                                        finish();
                                    }else {
                                        finish();
                                    }
                                    Log.i("xucc", "===============" + account.toString());
                                } catch (Exception e1) {
                                    Log.i("xucc", Log.getStackTraceString(e1));
                                } finally {
                                }
                            }
                        });
    }

    /**
     * 获取access_token的URL（微信）
     *
     * @param code 授权时，微信回调给的
     * @return URL
     */
    private String getCodeRequest(String code) {
        String result = null;
        GetCodeRequest = GetCodeRequest.replace("APPID",
                urlEnodeUTF8(BuildConfig.WEIXIN_APP_ID));
        GetCodeRequest = GetCodeRequest.replace("SECRET",
                urlEnodeUTF8("7e1c04cccb29d974150da02c8ade9c3d"));
        GetCodeRequest = GetCodeRequest.replace("CODE", urlEnodeUTF8(code));
        result = GetCodeRequest;
        return result;
    }

    private String urlEnodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // 解析返回的数据
    private void parseJSONWithGSON(String jsonData) {
        // 使用轻量级的Gson解析得到的json
        Gson gson = new Gson();
        WeixinBean appList = gson.fromJson(jsonData,
                new TypeToken<WeixinBean>() {
                }.getType());
        // 控制台输出结果，便于查看
        String str = getUserInfo(appList.getAccess_token(), appList.getOpenid());
        getUserInfo(str);


    }


    /**
     * 获取用户个人信息的URL（微信）
     *
     * @param access_token 获取access_token时给的
     * @param openid       获取access_token时给的
     * @return URL
     */
    private String getUserInfo(String access_token, String openid) {
        String result = null;
        GetUserInfo = GetUserInfo.replace("ACCESS_TOKEN",
                urlEnodeUTF8(access_token));
        GetUserInfo = GetUserInfo.replace("OPENID", urlEnodeUTF8(openid));
        result = GetUserInfo;
        return result;
    }

}
